import React, { Component } from "react";
import GridTable from '../../components/display/gridTable';
import { findPrivateOrderList, prefixFile, privateTypeList } from "../../fetch/fetchApi";
import PropsType from "prop-types";
import { Button, Input, Row, Col, Select, Tooltip } from 'antd';
import locale from "antd/lib/date-picker/locale/zh_CN";
import { DatePicker, message } from "antd/lib/index";
import AreaPicker from '../../components/dataEntry/areaPicker';
import moment from 'moment';
const {RangePicker} = DatePicker;
const Option = Select.Option;


class PrivateStubOrder extends Component {

    constructor(props) {
        super(props);
        this.props = props;
        this.state = {
            gridData: [],
            loadingmes: '查询',
            exportMes: '导出',
            rangeValue: [moment(this.currentTime(7), 'YYYY-MM-DD'), moment(this.currentTime(), 'YYYY-MM-DD')],
            loading: !1,
            btnloading: !1,
            typeList: [],
            pagination: {
                total: 0
            }
        };
        this.init();
    }

    init() {
        this.query = {
            page: '1',
            pagecount: '10',
            startTime: moment(this.currentTime(7), 'YYYY-MM-DD').format('YYYY-MM-DD').toString(),
            endTime: moment(this.currentTime(), 'YYYY-MM-DD').format('YYYY-MM-DD').toString()
        };
        // 初始化私桩类型
        this.findPrivateTypeList();
        // 设置表头
        this.tableColumns = [
            {
                title: '平台订单号',
                dataIndex: 'key',
                key: 'key',
                className: 'column-nowrap',
                fixed: 'left',
                render: (text, record) => (
                <Tooltip placement="topLeft" title={text} >
                    {text}
                </Tooltip>)
            }, {
                title: '充电时间',
                dataIndex: 'chargeTimeRange',
                key: 'chargeTimeRange',
                className: 'column-nowrap',
                render: (text, record) => (
                <Tooltip placement="topLeft" title={text} >
                    {text}
                </Tooltip>)
            }, {
                title: '充电用户',
                dataIndex: 'account',
                key: 'account',
                className: 'column-nowrap'
            }, {
                title: '电桩编号',
                dataIndex: 'stubId',
                key: 'stubId',
                className: 'column-nowrap'
            }, {
                title: '电量（度）',
                dataIndex: 'electric',
                key: 'electric',
                className: 'column-nowrap'
            }, {
                title: '时长（分）',
                dataIndex: 'chargeTime',
                key: 'chargeTime',
                className: 'column-nowrap'
            }, {
                title: '订单金额（元）',
                dataIndex: 'orderFee',
                key: 'orderFee',
                className: 'column-nowrap'
            }, {
                title: '折扣类型',
                dataIndex: 'discountTypeStr',
                key: 'discountTypeStr',
                className: 'column-nowrap',
                render: text => <div>
                        <Tooltip placement="topLeft" title={text} arrowPointAtCenter>
                          {text}
                        </Tooltip>
                    </div>

            }, {
                title: '折扣金额（元）',
                dataIndex: 'discountFee',
                key: 'discountFee',
                className: 'column-nowrap'
            }, {
                title: '应付金额（元）',
                dataIndex: 'fee',
                key: 'fee',
                className: 'column-nowrap'
            }, {
                title: '抵扣金额（元）',
                dataIndex: 'voucherMoney',
                key: 'voucherMoney',
                className: 'column-nowrap'
            }, {
                title: '实付金额（元）',
                dataIndex: 'accountMoney',
                key: 'accountMoney',
                className: 'column-nowrap'
            }, {
                title: '平台服务费（元）',
                dataIndex: 'appServiceFee',
                key: 'appServiceFee',
                className: 'column-nowrap'
            }, {
                title: '充电类型',
                dataIndex: 'chargeType',
                key: 'chargeType',
                className: 'column-nowrap'
            }, {
                title: '私桩类型',
                dataIndex: 'stubKindName',
                key: 'stubKindName',
                className: 'column-nowrap'
            }, {
                title: '所属城市',
                dataIndex: 'cityStr',
                key: 'cityStr',
                className: 'column-nowrap'
            }, {
                title: '充电状态',
                dataIndex: 'status',
                key: 'status',
                className: 'column-nowrap',
                render: (text, record) => (
                    <div>{text === 1 ? '充电中' : '订单结束'}</div>
                )
            }, {
                title: '停止原因',
                dataIndex: 'endInfo',
                key: 'endInfo',
                className: 'column-nowrap',
                render: text => <div>
                        <Tooltip placement="topLeft" title={text} arrowPointAtCenter>
                          {text}
                        </Tooltip>
                    </div>
            }
        ];
    }

    // 获取系统时间
    currentTime(days) {
        let date = new Date(); // 获取当前时间
        if (days && days > 0) {
            date.setDate(date.getDate() - days);
            return date;
        }
        return date;
    }

    // 提交查询
    queryChargeInfo() {
        this.query.page = '1';
        this.state.pagination.current = 1;
        this.setState({
            pagination: this.state.pagination
        });
        this.buildingApplyCb();
    }

    // 订单结束时间修改
    onDataChange(e) {
        if (e[1] - e[0] > 7 * 24 * 60 * 6e4) {
            message.warn('选择范围请在7天内', 1);
            this.setState({
                'rangeValue': null
            });
            this.query['startTime'] = '';
            this.query['endTime'] = '';
            return;
        }
        ;
        this.setState({
            'rangeValue': e
        });
        this.query['startTime'] = e[0] && e[0].format('YYYY-MM-DD').toString();
        this.query['endTime'] = e[1] && e[1].format('YYYY-MM-DD').toString();
    }

    // 打开tab
    openTab(param, e) {
        this.props.onAdd.bind(window.LayoutTab)(e, param);
    }

    // 注入用户账号
    pileAccountInputHandler(e) {
        this.query['account'] = e.target.value.toString();
    }

    // 注入电桩编号
    pileCodeInputHandler(e) {
        this.query['stubId'] = e.target.value.toString();
    }

    // 注入折扣类型
    discountTypeInputHandler(e) {
        if (!isNaN(parseInt(e))) {
            this.query['discountType'] = parseInt(e);
        } else {
            this.query['discountType'] = null;
        }
    }

    // 注入充电类型
    chargeTypeInputHandler(e) {
        if (!isNaN(parseInt(e))) {
            this.query['chargeType'] = parseInt(e);
        } else {
            this.query['chargeType'] = null;
        }
    }

    // 注入私桩类型
    szTypeInputHandler(e) {
        this.query['stubKindId'] = e;
    }

    // 注入充电状态类型
    stateTypeInputHandler(e) {
        this.query['status'] = e;
    }

    // 私桩订单列表查询
    async findPrivateOrderList() {
        this.setState({
            loading: !0,
            btnloading: !0
        });
        try {
            const resData = await findPrivateOrderList(this.query);
            if (resData.data.code === '200') {
                const pagination = {
                    total: resData.data.pageLimit.totalCount,
                    onShowSizeChange: (current) => {
                        this.turnPage(current)
                    },
                    onChange: (current) => {
                        this.turnPage(current)
                    }
                }
                this.setState({
                    pagination
                });
                return resData.data.data;
            }
        } catch ( e ) {
            console.log(e);
        }
    }

    // 私桩类型列表获取
    async findPrivateTypeList() {
        try {
            const resData = await privateTypeList();
            if (resData.data.code === '200') {
                if (resData.data.data) {
                    console.log(this);
                    this.setState({
                        typeList: [
                            <Select placeholder="私桩类型" onChange={this.szTypeInputHandler.bind(this)}>
                                <Option value='' key=''>全部</Option>
                                {
                            resData.data.data.map((item) => {
                                console.log(item);
                                return <Option value={item.stubTypeId} key={item.stubTypeId}>{item.stubTypeName}</Option>
                            })
                            }
                            </Select>
                        ]
                    })
                }
            }
        } catch ( e ) {
            console.log(e);
        }
    }

    // 数据导出
    async exportData() {
        // 判断导出参数
        if (!this.query.startTime || !this.query.endTime) {
            message.warn('请选择订单结束时间', 1);
            return;
        }

        let excelUrl = prefixFile + '/privateStubOrder.do?';
        let paramUrl = '';
        Object.keys(this.query).map((key) => {
            paramUrl += key + '=' + this.query[key] + '&';
        });
        // 截取掉最后一个&符号
        if (paramUrl.length > 0) {
            paramUrl = paramUrl.substr(0, paramUrl.length - 1)
        }

        window.location.href = excelUrl + paramUrl;
    }

    // 跳转页码
    turnPage(current) {
        this.query['page'] = current.toString();
        this.buildingApplyCb();
    }

    buildingApplyCb() {
        this.findPrivateOrderList().then((data) => {
            this.setState({
                loading: !1,
                btnloading: !1,
                gridData: data
            });
        });
    }

    // 获取选择的地址编码
    onPickArea(val) {
        if (val.length) {
            // 精确到市级，传4位就行了
            // this.query['city'] = val[1] + '00';
            this.query['city'] = val[1];
        } else {
            this.query['city'] = '';
        }
    }

    render() {
        const Content = <div className="sc-page-content">
            <div className="page-toolbar">
                <Row gutter={8}>
                    <Col lg={3} xl={3}>
                        <label>订单结束时间</label>
                    </Col>
                    <Col lg={5} xl={5}>
                        <RangePicker value={this.state.rangeValue}
        onChange={this.onDataChange.bind(this)} locale={locale} format="YYYY-MM-DD"/>
                    </Col>
                    <Col lg={4} xl={4}>
                        <Input placeholder="用户账号精确查询" onChange={this.pileAccountInputHandler.bind(this)}/>
                    </Col>
                    <Col lg={4} xl={4}>
                        <Input placeholder="电桩编号精确查询" onChange={this.pileCodeInputHandler.bind(this)}/>
                    </Col>
                    <Col lg={4} xl={4}>
                        <Select placeholder="折扣类型" onChange={this.discountTypeInputHandler.bind(this)}>
                            <Option value="">全部</Option>
                            <Option value="0">星充APP大客户折扣</Option>
                            <Option value="1">星充APP用户等级折扣</Option>
                            <Option value="2">桩群折扣 </Option>
                            <Option value="3">商户折扣（之前的白名单用户）</Option>
                            <Option value="5">私桩桩主折扣</Option>
                            <Option value="6">私桩后台活动折扣</Option>
                            <Option value="7">商户投资人折扣（新桩群折扣）</Option>
                            <Option value="8">私桩用户组折扣</Option>
                        </Select>
                    </Col>
                    <Col lg={4} xl={4}>
                        <Select placeholder="充电类型" onChange={this.chargeTypeInputHandler.bind(this)}>
                            <Option value="">全部</Option>
                            <Option value="0">自充电</Option>
                            <Option value="1">共享充电</Option>
                            <Option value="2">白名单充电</Option>
                        </Select>
                    </Col>
                </Row>
                <Row gutter={8}>
                    <Col lg={4} xl={4} className="whole-fill">
                        {this.state.typeList}
                    </Col>
                    <Col lg={2} xl={2}>
                        <label>所属城市</label>
                    </Col>
                    <Col lg={6} xl={6}>
                        <AreaPicker pickAreaHandler={this.onPickArea.bind(this)}/>
                    </Col>
                    <Col lg={4} xl={4} className="whole-fill">
                        <Select placeholder="充电状态" onChange={this.stateTypeInputHandler.bind(this)}>
                            <Option value="">全部</Option>
                            <Option value="1">充电中</Option>
                            <Option value="9">完成订单</Option>
                        </Select>
                    </Col>
                    <div  className="button-inlineBlock">
                        <Button type="primary" onClick={this.queryChargeInfo.bind(this)}>{this.state.loadingmes}</Button>
                    </div>
                    <div  className="button-inlineBlock">
                        <Button type="primary" icon="download" onClick={this.exportData.bind(this)}>{this.state.exportMes}</Button>
                    </div>
                </Row>
            </div>
            <div className="page-panel">
                <GridTable postyle="table-center" data={this.state.gridData} columns={this.tableColumns} loading={this.state.loading} pagination={this.state.pagination}/>
            </div>
        </div>;

        return Content;
    }

}

export default PrivateStubOrder;

PrivateStubOrder.propTypes = {
    onAdd: PropsType.func
}